<?php

namespace App\Controller;


use App\Base\ErrCode;
use App\Base\Response;
use App\Logic\UserLogic;

class User
{
    use Response;

    /**
     * 注册
     */
    public function register()
    {
        $param = myTrim($_REQUEST);
        $userLogic = new UserLogic();
        if (empty($param['username'])) {
            self::returnJson(ErrCode::$failCode, [], '请输入用户名');
        }

        if (mb_strlen($param['username']) < 2 || mb_strlen($param['username']) > 50) {
            self::returnJson(ErrCode::$failCode, [], '用户名须少于2个字符且大于8个字符');
        }

        if (empty($param['password'])) {
            self::returnJson(ErrCode::$failCode, [], '请输入密码');
        }

        if (!matchPwd($param['password'])) {
            self::returnJson(ErrCode::$failCode, [], '密码须6-20位包含数字跟字母组成，可以有符号，但不能有空格');
        }

        if ($param['password'] != $param['repeatPassword']) {
            self::returnJson(ErrCode::$failCode, [], '两次密码输入不一致');
        }

        self::returnJson(...$userLogic->register($param));
    }

    /**
     * 登录
     */
    public function login()
    {
        $param = myTrim($_REQUEST);
        $userLogic = new UserLogic();
        if (empty($param['username'])) {
            return self::returnJson(ErrCode::$failCode, [], '请输入用户名');
        }
        if (empty($param['password'])) {
            return self::returnJson(ErrCode::$failCode, [], '请输入密码');
        }
        return self::returnJson(...$userLogic->login($param));
    }

    /**
     * 刷新token
     */
    public function refreshToken()
    {
        self::returnJson(...(new UserLogic())->refreshToken());
    }
}